package net.thetabx.ftdba.activities;

import net.thetabx.ftdba.GlobalData;
import net.thetabx.ftdba.R;
import net.thetabx.ftdba.RStatus;
import net.thetabx.ftdba.Userstats;
import net.thetabx.ftdba.http.HttpManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    static final int LOGIN_REQUEST = 0;
    
    private TextView txtStatus;
    private TextView txtNickname;
    private TextView txtPM;
    private TextView txtUpload;
    private TextView txtDownload;
    private TextView txtRatio;
    private TextView txtBuffer;
    private TextView txtGUpload;
    private TextView txtGDownload;
    private TextView txtGRatio;
    private TextView txtGBuffer;
    private TextView txtSeedtime;
    private TextView txtSltr;
    private Button btnDisconnect;
    
    private HttpManager http;
    private Userstats us;
    private SharedPreferences settings;
    private Resources res;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        res = getResources();
        txtStatus = (TextView)findViewById(R.id.txtMainStatus);
        txtNickname = (TextView)findViewById(R.id.txtStatsNickname);
        txtPM = (TextView)findViewById(R.id.txtStatsMP);
        txtUpload = (TextView)findViewById(R.id.txtStatsUpload);
        txtDownload = (TextView)findViewById(R.id.txtStatsDownload);
        txtRatio = (TextView)findViewById(R.id.txtStatsRatio);
        txtBuffer = (TextView)findViewById(R.id.txtStatsBuffer);
        txtGUpload = (TextView)findViewById(R.id.txtStatsGUpload);
        txtGDownload = (TextView)findViewById(R.id.txtStatsGDownload);
        txtGRatio = (TextView)findViewById(R.id.txtStatsGRatio);
        txtGBuffer = (TextView)findViewById(R.id.txtStatsGBuffer);
        txtSeedtime = (TextView)findViewById(R.id.txtStatsSeedtime);
        txtSltr = (TextView)findViewById(R.id.txtStatsSLTR);
        
        btnDisconnect = (Button)findViewById(R.id.btnDisconnect);
        btnDisconnect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(http.isConnected())
					disconnect();
				else {
					connectorView();
				}
			}
		});

        // Set saved options for httpManager
        settings = getSharedPreferences("LoginCreds", MODE_PRIVATE);
        String cookie = settings.getString("cookie", "");
        String token = settings.getString("token", "");
        Boolean proxy = settings.getBoolean("proxy", true);
        Boolean secure = settings.getBoolean("secure", true);
        Boolean remember = settings.getBoolean("remember", false);
        
        http = GlobalData.getHttpManager();
        if(proxy && !http.isProxified())
        	http = GlobalData.newHttpManager(true);
        
        if(!proxy && http.isProxified())
        	http = GlobalData.newHttpManager(false);
        
        http.setSecure(secure);
        
        if(remember && ((proxy && token != "") || (!proxy && cookie != ""))) {
        	http.setCookie(token);
			getUserstats();
        }
        else
        	connectorView();
    }
    
    public void connectorView() {
    	Intent i = new Intent(this, ConnectorActivity.class);
		startActivityForResult(i, LOGIN_REQUEST);
    }
    
    public void getUserstats() {
    	class UserstatsRetriever extends AsyncTask<String, Boolean, RStatus> {
    		ProgressDialog userstatsDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			userstatsDialog = ProgressDialog.show(MainActivity.this, "", res.getString(R.string.getting_userstats), true, false);
    		}
    		
    		@Override
    		protected RStatus doInBackground(String... params) {
    			if(http == null)
    				return RStatus.NO_HTTP;
    			
    			us = new Userstats(http);
    			if(us.getStatus() != RStatus.ENDED)
    				return us.getStatus();
    			
    			
    			return RStatus.ENDED;
    		}
    		@Override
    		protected void onPostExecute(RStatus status) {
    			userstatsDialog.dismiss();
    			if(status == RStatus.ENDED) {
    				http.setConnected(true);
    				//setStatusText(res.getString(R.string.connected));
    				displayUserstats();
    			}
    			else {
    				setStatusText(res.getString(R.string.cookie_dead));
    				connectorView();
    				//setStatusText(status.toString());
    			}
    		}
    	}
    	
    	new UserstatsRetriever().execute();
    }
    
    public void displayUserstats() {
    	setStatusText(String.format(res.getString(R.string.connected_as), us.getNickname()));
    	setText(txtNickname, us.getNickname());
    	setText(txtPM, String.valueOf(us.getnMp()));
    	setText(txtUpload, us.getUpload());
    	setText(txtDownload, us.getDownload());
    	setText(txtRatio, us.getRatio());
    	setText(txtBuffer, us.getBuffer());
    	setText(txtGUpload, us.getGUpload());
    	setText(txtGDownload, us.getGDownload());
    	setText(txtGRatio, us.getGRatio());
    	setText(txtGBuffer, us.getGBuffer());
    	setText(txtSeedtime, us.getSeedtime());
    	setText(txtSltr, us.getSltr());
    }
    
    public void disconnect() {
    	setStatusText(res.getString(R.string.not_connected));
    	new Disconnector().execute();
    }
    
    public void setStatusText(final String str) {
    	setText(txtStatus, str);
    }
    
    public void setText(final TextView view, final String str) {
    	view.post(new Runnable() {
            public void run() {
            	view.setText(str);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (requestCode == LOGIN_REQUEST) {
        	if(resultCode == RESULT_OK) {
        		getUserstats();
        		setText(btnDisconnect, res.getString(R.string.disconnect));
            }
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	if(http.isConnected())
    		menu.findItem(R.id.menu_userstat).setVisible(false);
    	else
    		menu.close();
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_shoutbox: {
        		startActivity(new Intent(this, ShoutboxActivity.class));
        		return true;
            }
            case R.id.menu_userlist: {
        		startActivity(new Intent(this, UserlistActivity.class));
        		return true;
            }
            case R.id.menu_torrents: {
        		startActivity(new Intent(this, TorrentsListActivity.class));
        		return true;
            }
            case R.id.menu_options: {
        		startActivity(new Intent(this, OptionsActivity.class));
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public class Disconnector extends AsyncTask<String, Boolean, RStatus> {
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			setText(btnDisconnect, res.getString(R.string.connect));
			
			http.send("/?section=LOGOUT");
			http.destroyHttpClient();
			return RStatus.DISCONNECTED;
		}
	}
}